# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

from sqlalchemy import Table
from sqlalchemy.orm import mapper, relation
from lib.alembic.migration import MigrationContext
from lib.alembic.operations import Operations
from lib.alembic import op
from Environment import *
from web_lib.webutils import leggiInSessione
import Environment
from dao.DaoUtils import get_columns

schema = leggiInSessione(sezione="Main", chiave="schema")

try:
    #t_tipo_campo = Table("tipo_campo", Environment.meta, schema=Environment.mainSchema, autoload=True)
    t_campo = Table('campo', Environment.meta, schema=schema, autoload=True)
except:
    from data.tipoCampo import t_tipo_campo
    from data.campo import t_campo

from dao.Dao import Dao
from dao.TipoCampo import TipoCampo

if "visibile" not in get_columns(t_campo):
    conn = engine.connect()
    ctx = MigrationContext.configure(conn)
    op = Operations(ctx)
    op.add_column('campo',  Column('visibile', Boolean, default=True),schema=schema)


class Campo(Dao):

    def __init__(self, req=None):
        Dao.__init__(self, entity=self)

    def filter_values(self, k, v):
        if k == 'denominazione':
            dic = {k: t_campo.c.denominazione.ilike("%" + v + "%")}
        elif k == "idTipo":
            dic = {k: t_campo.c.id_tipo_campo == v}
        elif k == "idCampoList":
            dic = {k: t_campo.c.id.in_(v)}
        return  dic[k]

    @property
    def tipo_campo(self):
        if self.id_tipo_campo:
            a = TipoCampo().getRecord(id=self.id_tipo_campo)
            if a:
                return a.denominazione
        else:
            return ""

std_mapper_campo = mapper(Campo, t_campo, properties={
        #'tipo_campoo': relation(TipoCampo, backref='campo')
            }, order_by=t_campo.c.id)
